package com.sebiotec.driver.ui.fragment.history;

import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.allen.library.RxHttpUtils;
import com.sebiotec.basecommon.utils.base.BaseLazyLoadingFragment;
import com.sebiotec.basecommon.utils.tools.SoftKeyBoardListener;

import com.sebiotec.driver.R;
import com.sebiotec.driver.R2;
import com.sebiotec.driver.adapt.HistoryAdapt;
import com.sebiotec.driver.model.SearchEntrty;
import com.sebiotec.driver.viewmodel.HistoryViewModel;
import com.loonggg.weekcalendar.view.WeekCalendar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.statelayout.MultipleStatusView;
import com.xw.repo.XEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HisToryFragment extends BaseLazyLoadingFragment {
    @BindView(R2.id.iv_history_seach_book)
    ImageView ivHistorySeachBook;
    @BindView(R2.id.ed_history_seach)
    XEditText edHistorySeach;
    @BindView(R2.id.iv_search)
    ImageView ivSearch;
    @BindView(R2.id.rl_shape)
    RelativeLayout rlShape;
    @BindView(R2.id.week_calendar_history)
    WeekCalendar weekCalendarHistory;
    @BindView(R2.id.recy_history)
    RecyclerView recyHistory;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.multiple_status_view)
    MultipleStatusView multipleStatusView;
    private boolean isShow = true;
    private HistoryViewModel mHistoryViewModel;
    private HistoryAdapt adapt;
    private String mSearch;
    private String date;
    private int PageSize = 30;
    private int PageIndex = 1;
    @BindView(R2.id.card)
    LinearLayout card;
    private MiniLoadingDialog dialog;



    @Override
    protected String getLogTag() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.driver_fragment_history;
    }

    @Override
    protected void initView(View root) {
        mHistoryViewModel = ViewModelProviders.of(this).get(HistoryViewModel.class);

        initUi();
    }

    @Override
    protected void onFragmentResume() {
        super.onFragmentResume();
        if (dialog!=null){
            dialog.show();
        }else{
            dialog=new MiniLoadingDialog(getActivity(),getString(R.string.tip_loading_message));
            dialog.show();
        }
        initDatas();
    }


    private void initUi() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyHistory.setLayoutManager(linearLayoutManager);
        edHistorySeach.addTextChangedListener(textWatcher);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.setEnableLoadMore(true);
                PageIndex = 1;
                mHistoryViewModel.getHistoryData(date, mSearch,  PageIndex, PageSize, new HistoryViewModel.MyHistoryDataCallBack<Object>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onDataSuccessCallBack(Object o) {
                        refreshlayout.finishRefresh(/*,false*/);//传入false表示刷新失败
                        SearchEntrty rowsBeans = (SearchEntrty) o;
                        if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {
                            multipleStatusView.showEmpty();
                        } else {
                            List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
                            rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));
                            PageIndex++;
                            if (adapt != null) {
                                adapt.setNewData(rows);
                                recyHistory.setAdapter(adapt);
                            } else {
                                adapt = new HistoryAdapt();

                                adapt.addData(rows);
                                recyHistory.setAdapter(adapt);
                            }

                        }

                    }

                    @Override
                    public void onDataFailCallBack(Object o) {

                        refreshlayout.finishRefresh(false/*,false*/);//传入false表示刷新失败
                    }


                });

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                mHistoryViewModel.getHistoryData(date, mSearch, PageIndex, PageSize, new HistoryViewModel.MyHistoryDataCallBack<Object>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onDataSuccessCallBack(Object o) {


                        SearchEntrty rowsBeans = (SearchEntrty) o;
                        if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {

                            refreshlayout.setNoMoreData(true);

                        } else {
                            PageIndex++;
                            List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
//                            rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));

                            refreshlayout.finishLoadMore();
                            adapt.addData(rows);


                        }


                    }

                    @Override
                    public void onDataFailCallBack(Object o) {
                        refreshlayout.finishLoadMore(false/*,false*/);//传入false表示加载失败

                    }


                });


            }
        });
        edHistorySeach.setOnXFocusChangeListener(new XEditText.OnXFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    rlShape.setBackground(getActivity().getDrawable(R.drawable.ll_half_shape_ed));
                    ivSearch.setImageResource(R.drawable.seach_white);
                } else {
                    // 此处为失去焦点时的处理内容
                    rlShape.setBackground(getActivity().getDrawable(R.drawable.ll_half_shape));
                    ivSearch.setImageResource(R.drawable.search);
                }
            }
        });
        edHistorySeach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edHistorySeach.setFocusable(true);
                edHistorySeach.setFocusableInTouchMode(true);
                edHistorySeach.requestFocus();
            }
        });
        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                edHistorySeach.setFocusable(false);
            }
        });
        weekCalendarHistory.setOnDateClickListener(new WeekCalendar.OnDateClickListener() {
            @Override
            public void onDateClick(String time) {
                multipleStatusView.showLoading();
                date= time;
                PageIndex = 1;
                refreshLayout.setNoMoreData(false);
                getFristData();
            }
        });
    }



    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mSearch=edHistorySeach.getText().toString();
        }
    };

    @OnClick({R2.id.iv_history_seach_book, R2.id.ed_history_seach, R2.id.iv_search})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_history_seach_book) {

            if (isShow) {
                card.setVisibility(View.GONE);
                isShow = false;
                date="";
                PageIndex=1;
                refreshLayout.setNoMoreData(false);

                getFristData();

            } else {
                card.setVisibility(View.VISIBLE);
                isShow = true;
            }


        } else if (id == R.id.ed_history_seach) {
        } else if (id == R.id.iv_search) {
            multipleStatusView.showLoading();
            mSearch= edHistorySeach.getTextEx().toString().trim();
            PageIndex = 1;
            refreshLayout.setNoMoreData(false);
            getFristData();
        }
    }


    public void initDatas() {
        PageIndex = 1;
        refreshLayout.setNoMoreData(false);
        getFristData();
        multipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multipleStatusView.showLoading();
                PageIndex = 1;
                refreshLayout.setNoMoreData(false);
                getFristData();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog!=null){
            dialog.dismiss();
            dialog=null;
        }
        RxHttpUtils.cancel("JobHis");
    }

    public void getFristData() {
        mHistoryViewModel.getHistoryData(date, mSearch, PageIndex, PageSize, new HistoryViewModel.MyHistoryDataCallBack<Object>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onDataSuccessCallBack(Object o) {
                if (dialog!=null){
                    dialog.dismiss();
                }
                SearchEntrty rowsBeans = (SearchEntrty) o;
                if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {
                    multipleStatusView.showEmpty();
                } else {
                    List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
                    rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));
                    PageIndex++;
                    multipleStatusView.showContent();
                    if (adapt != null) {
                        adapt.setNewData(rows);
                    } else {
                        adapt = new HistoryAdapt();
                        recyHistory.setAdapter(adapt);
                        adapt.setNewData(rows);
                    }

                }

            }

            @Override
            public void onDataFailCallBack(Object o) {
                if (dialog!=null){
                    dialog.dismiss();
                }
                if (multipleStatusView!=null){
                    multipleStatusView.showError();
                }

            }


        });

    }
}
